package com.guo.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guo.cmn.listener.DictListener;
import com.guo.cmn.mapper.DictMapper;
import com.guo.cmn.service.DictService;
import com.guo.model.cmn.Dict;
import com.guo.vo.cmn.DictEeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gfj
 * @Date 2022/1/18 11:54
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

	@Override
	public List<Dict> findChildData(long id) {
		QueryWrapper<Dict> wrapper = new QueryWrapper();
		wrapper.eq("parent_id",id);
		List<Dict> dictList = baseMapper.selectList(wrapper);
		log.info("根据parent_id查出来的数据：{}",dictList);
		for(Dict dict : dictList){
			Long id1 = dict.getId();
			boolean hasChild = this.isHasChild(id1);
			dict.setHasChildren(hasChild);
		}
		return dictList;
	}

	@Override
	public void exportDictData(HttpServletResponse response) {
		try {
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode("数据字典","utf-8");
			response.setHeader("Content-disposition","attachment;filename="+fileName+
			".xlsx");
			List<Dict> dictList = baseMapper.selectList(null);
			List<DictEeVo> list = new ArrayList<>();
			for (Dict dict : dictList) {
				DictEeVo dictEeVo = new DictEeVo();
				BeanUtils.copyProperties(dict,dictEeVo);
				list.add(dictEeVo);
			}
			EasyExcel.write(response.getOutputStream(),DictEeVo.class)
					.sheet().
					doWrite(list);

		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void importDictData(MultipartFile file) {
		try {
			log.info("进来了");
			InputStream inputStream = file.getInputStream();
			//文件流，上传类，监听上传处理
			EasyExcel.read(inputStream,DictEeVo.class,new DictListener(baseMapper))
					.sheet().doRead();
		}catch (Exception e){

		}
	}

	private boolean isHasChild(long id){
		QueryWrapper<Dict> wrapper = new QueryWrapper<>();
		wrapper.eq("parent_id",id);
		Integer count = baseMapper.selectCount(wrapper);
		if (count>0){
			return true;
		}
		return false;
	}
}
